//
//  RecordViewController.m
//  HuateVideo
//
//  Created by  on 12-5-27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "RecordViewController.h"
#import "Movie.h"
#import "PicShowViewController.h"
#import "DetailViewController.h"
@interface RecordViewController ()

@end

@implementation RecordViewController
@synthesize isPlayRecord;
-(void)dealloc{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
    [array release];
    [videoArray release];
    [musicArray release];
    [picArray release];
    [downloaderArray release];
    [super dealloc];
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (downloaderArray.count) {
        [downloaderArray makeObjectsPerformSelector:@selector(cancelDownload)];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshRecord) name:REFRESHRECORD object:nil];
        videoArray=[[NSMutableArray alloc] init];
        musicArray=[[NSMutableArray alloc] init];
        picArray=[[NSMutableArray alloc] init];
    }
    return self;
}
- (void)cleanList{
    [array removeAllObjects];
    [table reloadData];
    if (isPlayRecord) {
		[UserDefaults setObject:array forKey:PlAYRECORDING_KEY];
	}else {
		[UserDefaults setObject:array forKey:COLLECTION_VIDEOS_STORE_KEY];
	}

}

- (void)btnEvent:(UIButton*)button{
    if (button.tag>=10000 && button.tag < 20000) {
        id temp = [[tempArray objectAtIndex:button.tag - 10000] retain];
        
        if (currentSegIndex==2) {
            PicShowViewController*picshow=[[PicShowViewController alloc] init];
            picshow.imgCount=0;
            picshow.picListArray=[NSArray arrayWithObject:temp];
            [self.navigationController pushViewController:picshow animated:YES];
            [picshow release];
        }
        else {
            if ([[temp Type] intValue] == MovieChannelTypeSeries) {
                
                NSMutableArray *tmp = [NSMutableArray array];
                for (int i=0; i<[[temp File_path_array] count]; i++) {
                    if ([[[temp File_path_array] objectAtIndex:i] isKindOfClass:[NSString class]]) {
                        if ([[[temp File_path_array] objectAtIndex:i] length]>5) {
                            [tmp addObject:[[temp File_path_array] objectAtIndex:i]];
                        }
                    }
                }
                [temp setFile_path_array:tmp];
                
                [temp setOrderNUM:0];
            }
//            [[NSNotificationCenter defaultCenter] postNotificationName:PLAYMOVIENOTIFICATION object:temp];
            DetailViewController *detailViewController = [[DetailViewController alloc]init];
            detailViewController.movie = temp;
            detailViewController.type = 2;
            detailViewController.channelType = [temp detailType];
            [self.navigationController pushViewController:detailViewController animated:YES];
            [detailViewController release];

        }
    }
    else {
        id mov=[tempArray objectAtIndex:button.tag - 20000];
        [tempArray removeObject:mov];
        [table reloadData];
        [array removeObject:mov];
		if (isPlayRecord) {
			[UserDefaults setObject:array forKey:PlAYRECORDING_KEY];
		}else {
			[UserDefaults setObject:array forKey:COLLECTION_VIDEOS_STORE_KEY];
		}

    }
}
- (void)refreshRecord{
	if (!isPlayRecord) {
		return;
	}
	[array removeAllObjects];
	[array addObjectsFromArray:[UserDefaults objectForKey:PlAYRECORDING_KEY]];
    NSLog(@"%d",array.count);
    [self cateArray];
	[table reloadData];
}
-(void)cateArray{
    [musicArray removeAllObjects];
    [videoArray removeAllObjects];
    [picArray removeAllObjects];
    for (int i=0; i<array.count; i++) {
        id m=[array objectAtIndex:i];
        if ([m detailType]==MovieChannelTypeMusic) {
            [musicArray addObject:m];
        }else if ([m detailType]==MovieChannelTypePic) {
            [picArray addObject:m];
        }else {
            [videoArray addObject:m];
        }
    }
    if (currentSegIndex==0) {
        tempArray=videoArray;
    }else if (currentSegIndex==1) {
        tempArray=musicArray;
    }else if (currentSegIndex==2) {
        tempArray=picArray;
    }

    NSLog(@"%@",videoArray);
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=TOOLBAR_TINTCOLOR; 
	if (isPlayRecord) {
		array = [[NSMutableArray alloc]initWithArray:[UserDefaults objectForKey:PlAYRECORDING_KEY]];
	}else {
		array = [[NSMutableArray alloc]initWithArray:[UserDefaults objectForKey:COLLECTION_VIDEOS_STORE_KEY]];
	}
    [self cateArray];
	
    downloaderArray = [[NSMutableArray alloc]init];
    
	// Do any additional setup after loading the view.
    UIBarButtonItem* rightb=[[UIBarButtonItem alloc] initWithTitle:LS(@"清空") style:UIBarButtonItemStylePlain target:self action:@selector(cleanList)];
    //self.navigationItem.rightBarButtonItem=rightb;
    [rightb release];

    table=[[UITableView alloc] initWithFrame:CGRectMake(0, 40, 320, 460-44-49-40) style:UITableViewStylePlain];
    table.delegate=self;
    table.dataSource=self;
    table.opaque=NO;
    table.allowsSelection=NO;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    table.backgroundColor=[UIColor clearColor];
    [self.view addSubview:table];
    [table release];
    [self initTopView];

}
- (void)segmentChanged:(UISegmentedControl *)sender{
    currentSegIndex=sender.selectedSegmentIndex;
    if (currentSegIndex==0) {
        tempArray=videoArray;
    }else if (currentSegIndex==1) {
        tempArray=musicArray;
    }else if (currentSegIndex==2) {
        tempArray=picArray;
    }
    [table reloadData];
}
- (void)initTopView{
    currentSegIndex=0;
    UISegmentedControl *segmentControl ;
    segmentControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:LS(@"视频"),LS(@"音乐"),LS(@"图片"),nil]];
        
    segmentControl.frame = CGRectMake(40, 7, 195, 26);
    segmentControl.center=CGPointMake(160, 20);
    segmentControl.tintColor = TOOLBAR_TINTCOLOR;
    [segmentControl setSegmentedControlStyle:UISegmentedControlStyleBar];
    [segmentControl addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmentControl];
    [segmentControl release];
    [segmentControl setSelectedSegmentIndex:currentSegIndex];

    UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 39, 320, 2)];
    line.image = [UIImage imageNamed:@"fengexian.png"];
    [self.view addSubview:line];
    [line release];
    [self segmentChanged:segmentControl];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 115;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tempArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	static NSString* ListIdentifier = @"ListIdentifier";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ListIdentifier];
	
	if (cell == nil)
	{
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListIdentifier];
		//cell.selectionStyle = UITableViewCellSelectionStyleNone;  //去掉选中时的颜色
	}
	
	for (UIView* subView in [cell.contentView subviews])
	{
		[subView removeFromSuperview];
	}
    
	if (indexPath.row < [tempArray count]) {
        id movie = [tempArray objectAtIndex:indexPath.row];
        
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 75, 95)];
        image.tag=1000;
        [cell.contentView addSubview:image];
        [image release];
        NSString*imgurl=[movie News_pic];
        NSLog(@"%@=========\n%@",[movie News_title],imgurl);
        if ((![imgurl isEqual:[NSNull null]])&&imgurl.length>0) {
            UIImage*tImg=[movie iconImg];
			if (tImg) {
				image.image=[movie iconImg];
            }else {
                image.image = [UIImage imageNamed:@"dengdai.png"];
				NSDictionary* dic=[NSDictionary dictionaryWithObjectsAndKeys:movie,@"item",indexPath,@"rowNum",nil];
				[self performSelector:@selector(downImg:) withObject:dic afterDelay:0.2];
            }
        }
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(95, 10, 220, 20)];
        label.text = [movie News_title];
        label.textColor = LIGHT_COLOR;
        label.font = [UIFont systemFontOfSize:16.0];
        label.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:label];
        [label release];
     //   if (isPlayRecord) {
//			if ([movie secondPlayed]>0) {
//				NSInteger seconds=[movie secondPlayed];
//				
//				label=[[UILabel alloc] initWithFrame:CGRectMake(95, 40, 100, 20)];
//				label.text=[NSString stringWithFormat:@"播放到:%d",[movie secondPlayed]];
//				label.textColor=LIGHT_COLOR;
//				label.font=[UIFont systemFontOfSize:15];
//				label.backgroundColor=[UIColor clearColor];
//				[cell.contentView addSubview:label];
//				[label release];
//			}
//		}
		
        UIButton *fabu = [UIButton buttonWithType:UIButtonTypeCustom];
        fabu.tag = 10000+indexPath.row;
        fabu.frame = CGRectMake(195, 80, 55, 25);
        fabu.titleLabel.font = [UIFont systemFontOfSize:12.0];
        [fabu setBackgroundImage:[UIImage imageNamed:@"liangzianniu.png"] forState:UIControlStateNormal];
        [fabu setTitle:LS(@"详情") forState:UIControlStateNormal];
        [fabu addTarget:self action:@selector(btnEvent:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:fabu];
        if ([movie detailType] == MovieChannelTypePic) {
            [fabu setTitle:LS(@"浏览") forState:UIControlStateNormal];
        }
        
        UIButton *shanchu = [UIButton buttonWithType:UIButtonTypeCustom];
        shanchu.tag = 20000+indexPath.row;
        shanchu.frame = CGRectMake(265, 80, 55, 25);
        shanchu.titleLabel.font = [UIFont systemFontOfSize:12.0];
        [shanchu setBackgroundImage:[UIImage imageNamed:@"liangzianniu.png"] forState:UIControlStateNormal];
        [shanchu addTarget:self action:@selector(btnEvent:) forControlEvents:UIControlEventTouchUpInside];
        [shanchu setTitle:LS(@"删除") forState:UIControlStateNormal];
        [cell.contentView addSubview:shanchu];

        if ([movie detailType]!=MovieChannelTypePic) {
            label = [[UILabel alloc]initWithFrame:CGRectMake(95, 35, 200, 20)];
            label.text = [NSString stringWithFormat:@"%@: %@",LS(@"导演"),[movie News_arg3]];
            label.textColor = [UIColor lightGrayColor];
            label.font = [UIFont systemFontOfSize:14.0];
            label.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:label];
            [label release];
            
            if ([movie detailType]==MovieChannelTypeNews) {
                label.text=[NSString stringWithFormat:@"%@: %@",LS(@"发布时间"),[movie News_pub_time]];
            }
            if ([movie detailType]==MovieChannelTypeMicroViedo) {
                label.text=[NSString stringWithFormat:@"%@: %@",LS(@"上传者"),[movie News_author]];
            }
            if ([movie detailType]==MovieChannelTypeOriginal) {
                label.text=[NSString stringWithFormat:@"%@: %@",LS(@"拍摄时间"),[movie News_arg5]];
            }
            if ([movie detailType]==MovieChannelTypeMusic) {
                label.text=[NSString stringWithFormat:@"%@: %@",LS(@"歌手"),[movie News_author]];
            }
            label = [[UILabel alloc]initWithFrame:CGRectMake(95, 60, 200, 20)];
            label.text = [NSString stringWithFormat:@"%@: %@",LS(@"主演"),[movie News_arg2]];
            label.textColor = [UIColor lightGrayColor];
            label.font = [UIFont systemFontOfSize:14.0];
            label.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:label];
            [label release];
            
            if ([movie detailType]==MovieChannelTypeNews) {
                label.frame=CGRectMake(95, 60, 200, 40);
                label.numberOfLines=0;
                //            label.text=@"乌鲁木齐6月开始进行田字工程施工，届时所有车辆需绕道行驶...";
            }
            if ([movie detailType]==MovieChannelTypeMicroViedo) {
                label.text=[NSString stringWithFormat:@"%@: %@",LS(@"上传时间"),[movie News_arg5]];
            }
            if ([movie detailType]==MovieChannelTypeMusic) {
                label.text=[NSString stringWithFormat:@"%@: %@",LS(@"专辑"),[movie News_arg1]];
            }
            if ([movie detailType]==MovieChannelTypeOriginal||[movie detailType]==MovieChannelTypeNews) {
                label.text=[NSString stringWithFormat:@"%@: %@",LS(@"摘要简介"),[movie News_content]];
            }
            if ([movie detailType]!=MovieChannelTypeMusic&&[movie detailType]!=MovieChannelTypeNews){
                label = [[UILabel alloc]initWithFrame:CGRectMake(95, 85, 200, 20)];
                label.text = [NSString stringWithFormat:@"%@: %d%@",LS(@"总播放"),[movie News_click_count],LS(@"次")];
                label.textColor = [UIColor lightGrayColor];
                label.font = [UIFont systemFontOfSize:14.0];
                label.backgroundColor = [UIColor clearColor];
                [cell.contentView addSubview:label];
                [label release];
            }
        }
        
        
        UIImageView *line = [[UIImageView alloc]initWithFrame:CGRectMake(0, 114, 320, 2)];
        line.image = [UIImage imageNamed:@"fengexian.png"];
        [cell.contentView addSubview:line];
        [line release];
    }
	
	cell.backgroundColor = [UIColor clearColor];

	
	return cell;
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)downImg:(NSDictionary*)dic {
	id movie=[dic valueForKey:@"item"];
	int tag=[[dic valueForKey:@"rowNum"] row];
	ImageDownloader* downloader=[[ImageDownloader alloc] init];
	downloader.imageURL=[movie News_pic];
	downloader.delegate=self;
	downloader.tag=tag;
	[downloader startDownload:YES];
	[downloaderArray addObject:downloader];
	[downloader release];
	
}

- (void)appImageDidLoad:(UIImage *)image withTag:(int)tag{
    NSLog(@"load ++++++++%d",tag);
	id t_movie=[array objectAtIndex:tag];
    UITableViewCell* cell=[table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:tag inSection:0]];
    UIImageView* img=(UIImageView*)[cell.contentView viewWithTag:1000];
    if (image) {
		[t_movie setIconImg:image];
        img.image=image;
    }
}

@end
